import 'dart:convert';
import 'dart:math';
import 'package:flutter/services.dart';
import '../models/word_card.dart';

Future<List<WordCard>> loadSampleWords() async {
  final manifestContent = await rootBundle.loadString('AssetManifest.json');
  final Map<String, dynamic> manifestMap = json.decode(manifestContent);
  final List<String> assetPaths = manifestMap.keys
      .where((String key) => key.startsWith('assets/data/words/cet4-all'))
      .toList()
    ..shuffle(Random());

  final List<WordCard> sampleWords = [];

  for (final String assetPath in assetPaths) {
    final String jsonString = await rootBundle.loadString(assetPath);
    final Map<String, dynamic> jsonData = json.decode(jsonString);
    sampleWords.add(WordCard.fromJson(jsonData));
  }

  // 生成复习序列
  final sequence = generateReviewSequence(sampleWords.length, 5);

  // 根据序列创建带重复的单词列表
  return sequence.map((index) => sampleWords[index]).toList();
}

// 记忆曲线序列生成算法
List<int> generateReviewSequence(int n, int m) {
  final events = <List<int>>[];
  for (int i = 0; i < n; i++) {
    events.add([i, i]); // 初始学习事件
    for (int r = 1; r <= m; r++) {
      final delta = (pow(2, r)).toInt();
      final pos = i + delta;
      events.add([pos, i]);
    }
  }
  events.sort(
      (a, b) => a[0] == b[0] ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));
  return events.map((e) => e[1]).toList();
}
